package com.bindapp.activity;

import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintSet;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bindapp.App;
import com.bindapp.R;
import com.bindapp.adapter.BdeviceAdapter;
import com.bindapp.databinding.ActivityDeivceplayBinding;
import com.bindapp.listener.RecyclerItemClick;
import com.bindapp.util.Static;
import com.bindapp.util.ezutil.AudioPlayUtil;
import com.bindapp.util.ezutil.DataManager;
import com.bindapp.util.ezutil.EZUtils;
import com.bindapp.util.ezutil.RealPlaySquareInfo;
import com.videogo.constant.IntentConsts;
import com.videogo.exception.BaseException;
import com.videogo.exception.InnerException;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZPlayer;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.videogo.realplay.RealPlayStatus;
import com.videogo.util.ConnectionDetector;
import com.videogo.util.LocalInfo;
import com.videogo.util.MediaScanner;
import com.videogo.util.RotateViewUtil;
import com.videogo.util.SDCardUtil;
import com.videogo.util.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by apple on 2018/7/10.
 */

public class DevicePlayActivity extends BaseActivity {
    private ActivityDeivceplayBinding binding;
    private AudioPlayUtil mAudioPlayUtil;
    private LocalInfo mLocalInfo;
    private RotateViewUtil mRecordRotateViewUtil;
    private RealPlayBroadcastReceiver mBroadcastReceiver;
    private RealPlaySquareInfo mRealPlaySquareInfo;
    private EZDeviceInfo mDeviceInfo = null;
    private EZCameraInfo mCameraInfo = null;
    private EZPlayer mEZPlayer = null;
    private String mRtspUrl = null;
    private SurfaceView mRealPlaySv = null;
    private SurfaceHolder mRealPlaySh = null;
    private String mVerifyCode;
    private int mOrientation = Configuration.ORIENTATION_PORTRAIT;
    private int mStatus = RealPlayStatus.STATUS_INIT;
    private boolean mIsOnStop = false, mIsRecording = false;
    private EZConstants.EZVideoLevel mCurrentQulityMode = EZConstants.EZVideoLevel.VIDEO_LEVEL_HD;
    private ConstraintSet mConstraintSet1, mConstraintSet2;
    private boolean isSet=false;

    private MaterialDialog setdialog;
    private BdeviceAdapter adapter;
    private List<Object> bdlist=new ArrayList<Object>();

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    protected void after() {
        super.after();
        handerBackToolar(getIntent().getStringExtra("title"));
        initData();
        initView();
    }

    private void initView() {
        isSet=getIntent().getBooleanExtra("isSet",false);
        binding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.activity_deivceplay, null, false);
        binding.setClick(new ViewClick());
        binding.soundsbtn.setTag(1);
        AddContentView(binding.getRoot());
        mRealPlaySv = binding.realplaysv;
        mRealPlaySh = mRealPlaySv.getHolder();

        if(isSet){
            binding.setbtn.setVisibility(View.VISIBLE);

            for(int i=0;i<3;i++){
                bdlist.add("1");
            }

            adapter=new BdeviceAdapter(DevicePlayActivity.this,bdlist,R.layout.item_bdvice_item,-1,new ItemClick());
            adapter.addHeadView(R.layout.item_bdvice_head);
            setdialog=new MaterialDialog.Builder(this).adapter(adapter,new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)).canceledOnTouchOutside(true).build();

        }else{
            binding.setbtn.setVisibility(View.GONE);
        }

        mConstraintSet1 = new ConstraintSet();
        mConstraintSet2 = new ConstraintSet();
        mConstraintSet1.clone(binding.constraintLayout);
        mConstraintSet2.clone(this, R.layout.activity_deivceplay2);

        binding.topbtn.setOnTouchListener(mOnTouchListener);
        binding.leftbtn.setOnTouchListener(mOnTouchListener);
        binding.rightbtn.setOnTouchListener(mOnTouchListener);
        binding.bottombtn.setOnTouchListener(mOnTouchListener);

        binding.soundbtn.setOnTouchListener(mOnTouchListener);

        binding.talkbackRv.post(new Runnable() {
            @Override
            public void run() {
                if (binding.talkbackRv != null) {
                    binding.talkbackRv.setMinRadiusAndDistance(50,
                            Utils.dip2px(DevicePlayActivity.this, 22));
                }
            }
        });
    }

    private void initData() {
        // 获取本地信息
        Application application = (Application) getApplication();
        mAudioPlayUtil = AudioPlayUtil.getInstance(application);
        // 获取配置信息操作对象
        mLocalInfo = LocalInfo.getInstance();
        // 获取屏幕参数
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mLocalInfo.setScreenWidthHeight(metric.widthPixels, metric.heightPixels);
        mLocalInfo.setNavigationBarHeight((int) Math.ceil(25 * getResources().getDisplayMetrics().density));

        mRecordRotateViewUtil = new RotateViewUtil();

        mBroadcastReceiver = new RealPlayBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mBroadcastReceiver, filter);

        mRealPlaySquareInfo = new RealPlaySquareInfo();
        Intent intent = getIntent();
        if (intent != null) {
            mCameraInfo = intent.getParcelableExtra(IntentConsts.EXTRA_CAMERA_INFO);
            mDeviceInfo = intent.getParcelableExtra(IntentConsts.EXTRA_DEVICE_INFO);
            mRtspUrl = intent.getStringExtra(IntentConsts.EXTRA_RTSP_URL);
            if (mCameraInfo != null) {
                mCurrentQulityMode = (mCameraInfo.getVideoLevel());
            }
            Static.myLog("rtspUrl:" + mRtspUrl);

            getRealPlaySquareInfo();
        }
        if (mDeviceInfo != null && mDeviceInfo.getIsEncrypt() == 1) {
            mVerifyCode = DataManager.getInstance().getDeviceSerialVerifyCode(mCameraInfo.getDeviceSerial());
        }
    }

    public class ItemClick implements RecyclerItemClick{

        @Override
        public void onItemClick(int position) {

        }

        @Override
        public void onItemLongClick(int position) {

        }

        @Override
        public void onMoreClick(View view, int position) {

        }
    }

    public class ViewClick {
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.setbtn:
                    setdialog.show();
                    break;

                /*case R.id.videobtn:
                    onRecordBtnClick();
                    break;
                case R.id.camerabtn:
                    onCapturePicBtnClick();
                    break;
                case R.id.soundsbtn:
                    TransitionManager.beginDelayedTransition(binding.constraintLayout);
                    mConstraintSet2.applyTo(binding.constraintLayout);
                    break;
                case R.id.nolookbtn:

                    break;

                case R.id.soundclose:
                    TransitionManager.beginDelayedTransition(binding.constraintLayout);
                    mConstraintSet1.applyTo(binding.constraintLayout);
                    break;*/
            }

        }
    }

    private View.OnTouchListener mOnTouchListener = new View.OnTouchListener() {


        @Override
        public boolean onTouch(View view, MotionEvent motionevent) {
            int action = motionevent.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    switch (view.getId()) {
                        case R.id.topbtn:
                            //setPtzDirectionIv(RealPlayStatus.PTZ_UP);
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandUp, EZConstants.EZPTZAction.EZPTZActionSTART);
                            break;
                        case R.id.leftbtn:
                            //setPtzDirectionIv(RealPlayStatus.PTZ_LEFT);
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandLeft, EZConstants.EZPTZAction.EZPTZActionSTART);
                            break;
                        case R.id.rightbtn:
                            //setPtzDirectionIv(RealPlayStatus.PTZ_RIGHT);
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandRight, EZConstants.EZPTZAction.EZPTZActionSTART);
                            break;
                        case R.id.bottombtn:
                            //setPtzDirectionIv(RealPlayStatus.PTZ_DOWN);
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandDown, EZConstants.EZPTZAction.EZPTZActionSTART);
                            break;
                        case R.id.soundbtn:
                            binding.talkbackRv.setVisibility(View.VISIBLE);
                            mEZPlayer.setVoiceTalkStatus(true);
                            break;
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    switch (view.getId()) {
                        case R.id.topbtn:
                            //setPtzDirectionIv(RealPlayStatus.PTZ_UP);
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandUp, EZConstants.EZPTZAction.EZPTZActionSTOP);
                            break;
                        case R.id.leftbtn:
                            //setPtzDirectionIv(RealPlayStatus.PTZ_LEFT);
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandLeft, EZConstants.EZPTZAction.EZPTZActionSTOP);
                            break;
                        case R.id.rightbtn:
                            //setPtzDirectionIv(RealPlayStatus.PTZ_RIGHT);
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandRight, EZConstants.EZPTZAction.EZPTZActionSTOP);
                            break;
                        case R.id.bottombtn:
                            //setPtzDirectionIv(RealPlayStatus.PTZ_DOWN);
                            ptzOption(EZConstants.EZPTZCommand.EZPTZCommandDown, EZConstants.EZPTZAction.EZPTZActionSTOP);
                            break;
                        case R.id.soundbtn:
                            binding.talkbackRv.setVisibility(View.GONE);
                            mEZPlayer.setVoiceTalkStatus(false);
                            break;
                    }
                    break;
            }

            return false;
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        if (mOrientation == Configuration.ORIENTATION_LANDSCAPE) {
            return;
        }
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                if (mRealPlaySv != null) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(mRealPlaySv.getWindowToken(), 0);
                }
            }
        }, 200);

        //initUI();
        mRealPlaySv.setVisibility(View.VISIBLE);
        Static.myLog("onResume real play status:" + mStatus);
        //LogUtil.infoLog(TAG, "onResume real play status:" + mStatus);
        if (mCameraInfo != null && mDeviceInfo != null && mDeviceInfo.getStatus() != 1) {
            if (mStatus != RealPlayStatus.STATUS_STOP) {
                //stopRealPlay();
            }
            //setRealPlayFailUI(getString(R.string.realplay_fail_device_not_exist));
        } else {
            if (mStatus == RealPlayStatus.STATUS_INIT || mStatus == RealPlayStatus.STATUS_PAUSE
                    || mStatus == RealPlayStatus.STATUS_DECRYPT) {
                // 开始播放
                startRealPlay();
            }
        }
        mIsOnStop = false;
    }


    private void startRealPlay() {
        Static.myLog("startRealPlay");

        if (mStatus == RealPlayStatus.STATUS_START || mStatus == RealPlayStatus.STATUS_PLAY) {
            return;
        }

        if (!ConnectionDetector.isNetworkAvailable(this)) {
            //setRealPlayFailUI(getString(R.string.realplay_play_fail_becauseof_network));//remark
            return;
        }

        mStatus = RealPlayStatus.STATUS_START;
        //setRealPlayLoadingUI();

        if (mCameraInfo != null) {
            if (mEZPlayer == null) {
                mEZPlayer = App.getOpenSDK().createPlayer(mCameraInfo.getDeviceSerial(), mCameraInfo.getCameraNo());
            }

            if (mEZPlayer == null)
                return;
            if (mDeviceInfo == null) {
                return;
            }
            if (mDeviceInfo.getIsEncrypt() == 1) {
                mEZPlayer.setPlayVerifyCode(DataManager.getInstance().getDeviceSerialVerifyCode(mCameraInfo.getDeviceSerial()));
            }

            mEZPlayer.setHandler(mHandler);
            mEZPlayer.setSurfaceHold(mRealPlaySh);
            mEZPlayer.startRealPlay();
        } else if (mRtspUrl != null) {
            mEZPlayer = App.getOpenSDK().createPlayerWithUrl(mRtspUrl);
            //mStub.setCameraId(mCameraInfo.getCameraId());////****  mj
            if (mEZPlayer == null)
                return;
            mEZPlayer.setHandler(mHandler);
            mEZPlayer.setSurfaceHold(mRealPlaySh);

            mEZPlayer.startRealPlay();
        }
        //updateLoadingProgress(0);
    }

    private void ptzOption(final EZConstants.EZPTZCommand command, final EZConstants.EZPTZAction action) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean ptz_result = false;
                try {
                    ptz_result = App.getOpenSDK().controlPTZ(mCameraInfo.getDeviceSerial(), mCameraInfo.getCameraNo(), command,
                            action, EZConstants.PTZ_SPEED_DEFAULT);
                } catch (BaseException e) {
                    e.printStackTrace();
                }
                Static.myLog("controlPTZ ptzCtrl result: " + ptz_result);
            }
        }).start();
        Static.myLog("over");
    }

    @Override
    protected void onStop() {
        super.onStop();
        /*if (mScreenOrientationHelper != null) {
            mScreenOrientationHelper.postOnStop();
        }*/

        //mHandler.removeMessages(MSG_AUTO_START_PLAY);
        //hidePageAnim();

        if (mCameraInfo == null && mRtspUrl == null) {
            return;
        }

        //closePtzPopupWindow();
        //closeTalkPopupWindow(true, false);
        if (mStatus != RealPlayStatus.STATUS_STOP) {
            mIsOnStop = true;
            stopRealPlay();
            mStatus = RealPlayStatus.STATUS_PAUSE;
            //setRealPlayStopUI();
        } else {
            //setStopLoading();
        }
        mRealPlaySv.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mEZPlayer != null) {
            mEZPlayer.release();

        }
        mHandler = null;

        if (mBroadcastReceiver != null) {
            // 取消锁屏广播的注册
            unregisterReceiver(mBroadcastReceiver);
            mBroadcastReceiver = null;
        }

        //mScreenOrientationHelper = null;
    }

    private void stopRealPlay() {
        Static.myLog("stopRealPlay");
        mStatus = RealPlayStatus.STATUS_STOP;

        //stopUpdateTimer();
        if (mEZPlayer != null) {
            //stopRealPlayRecord();

            mEZPlayer.stopRealPlay();
        }
        //mStreamFlow = 0;
    }


    private void getRealPlaySquareInfo() {
        if (TextUtils.isEmpty(mRtspUrl)) {
            return;
        }

        Uri uri = Uri.parse(mRtspUrl.replaceFirst("&", "?"));
        try {
            mRealPlaySquareInfo.mSquareId = Integer.parseInt(uri.getQueryParameter("squareid"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        try {
            mRealPlaySquareInfo.mChannelNo = Integer.parseInt(Utils.getUrlValue(mRtspUrl, "channelno=", "&"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        mRealPlaySquareInfo.mCameraName = uri.getQueryParameter("cameraname");
        try {
            mRealPlaySquareInfo.mSoundType = Integer.parseInt(uri.getQueryParameter("soundtype"));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        mRealPlaySquareInfo.mCoverUrl = uri.getQueryParameter("md5Serial");
        if (!TextUtils.isEmpty(mRealPlaySquareInfo.mCoverUrl)) {
            mRealPlaySquareInfo.mCoverUrl = mLocalInfo.getServAddr() + mRealPlaySquareInfo.mCoverUrl + "_mobile.jpeg";
        }
    }

    private class RealPlayBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
                /*closePtzPopupWindow();
                closeTalkPopupWindow(true, false);
                if (mStatus != RealPlayStatus.STATUS_STOP) {
                    stopRealPlay();
                    mStatus = RealPlayStatus.STATUS_PAUSE;
                    setRealPlayStopUI();
                }*/
            }
        }
    }

    //截图
    private void onCapturePicBtnClick() {

        //mControlDisplaySec = 0;
        if (!SDCardUtil.isSDCardUseable()) {
            // 提示SD卡不可用
            Static.showToast(this, getString(R.string.remoteplayback_SDCard_disable_use));
            return;
        }

        if (SDCardUtil.getSDCardRemainSize() < SDCardUtil.PIC_MIN_MEM_SPACE) {
            Static.showToast(this, getString(R.string.remoteplayback_capture_fail_for_memory));
            return;
        }

        if (mEZPlayer != null) {
            //mCaptureDisplaySec = 4;
            //updateCaptureUI();

            Thread thr = new Thread() {
                @Override
                public void run() {
                    Bitmap bmp = mEZPlayer.capturePicture();
                    if (bmp != null) {
                        try {
                            mAudioPlayUtil.playAudioFile(AudioPlayUtil.CAPTURE_SOUND);

                            // 可以采用deviceSerial+时间作为文件命名，demo中简化，只用时间命名
                            java.util.Date date = new java.util.Date();
                            final String path = Environment.getExternalStorageDirectory().getPath() + "/" + Static.FILERECORD + "/CapturePicture/" + String.format("%tY", date)
                                    + String.format("%tm", date) + String.format("%td", date) + "/"
                                    + String.format("%tH", date) + String.format("%tM", date) + String.format("%tS", date) + String.format("%tL", date) + ".jpg";

                            if (TextUtils.isEmpty(path)) {
                                bmp.recycle();
                                bmp = null;
                                return;
                            }
                            EZUtils.saveCapturePictrue(path, bmp);


                            MediaScanner mMediaScanner = new MediaScanner(DevicePlayActivity.this);
                            mMediaScanner.scanFile(path, "jpg");
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(DevicePlayActivity.this, getResources().getString(R.string.already_saved_to_volume) + path, Toast.LENGTH_SHORT).show();
                                }
                            });
                        } catch (InnerException e) {
                            e.printStackTrace();
                        } finally {
                            if (bmp != null) {
                                bmp.recycle();
                                bmp = null;
                                return;
                            }
                        }
                    }
                    super.run();
                }
            };
            thr.start();
        }
    }

    //拍照
    private void onRecordBtnClick() {
        if (mIsRecording) {
            binding.videobtn.setImageDrawable(ContextCompat.getDrawable(DevicePlayActivity.this,R.drawable.video1));
            stopRealPlayRecord();
            return;
        }

        if (!SDCardUtil.isSDCardUseable()) {
            // 提示SD卡不可用
            Utils.showToast(this, R.string.remoteplayback_SDCard_disable_use);
            return;
        }

        if (SDCardUtil.getSDCardRemainSize() < SDCardUtil.PIC_MIN_MEM_SPACE) {
            // 提示内存不足
            Utils.showToast(this, R.string.remoteplayback_record_fail_for_memory);
            return;
        }

        if (mEZPlayer != null) {
            //mCaptureDisplaySec = 4;
            //updateCaptureUI();

            mAudioPlayUtil.playAudioFile(AudioPlayUtil.RECORD_SOUND);

            // 可以采用deviceSerial+时间作为文件命名，demo中简化，只用时间命名
            java.util.Date date = new java.util.Date();
            String strRecordFile = Environment.getExternalStorageDirectory().getPath() + "/" + Static.FILERECORD + "/Records/" + String.format("%tY", date)
                    + String.format("%tm", date) + String.format("%td", date) + "/"
                    + String.format("%tH", date) + String.format("%tM", date) + String.format("%tS", date) + String.format("%tL", date) + ".mp4";

            if (mEZPlayer.startLocalRecordWithFile(strRecordFile)) {
                mIsRecording = true;
                binding.videobtn.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.cameraselect));
                //handleRecordSuccess(strRecordFile);
            } else {
                //handleRecordFail();
            }
        }
    }

    public void stopRealPlayRecord() {
        if (mEZPlayer == null || !mIsRecording) {
            return;
        }
        mIsRecording = false;
        Static.showToast(DevicePlayActivity.this, "已保存至相册");
        mAudioPlayUtil.playAudioFile(AudioPlayUtil.RECORD_SOUND);
        mEZPlayer.stopLocalRecord();
    }

}
